<template>
  <a-modal
    :title="form.id ? '编辑' : '创建'"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="信息">
            <a-form-model
                ref="ruleForm"
                :model="form"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-model-item label="名称" ref="name" prop="name">
                    <a-input
                        v-model="form.name"
                        placeholder="请输入租户名称"
                        @blur="
                        () => {
                            $refs.name.onFieldBlur();
                        }
                        "
                        :disabled="form.id ? true : false"
                    />
                </a-form-model-item>
                <a-form-model-item label="显示名称" ref="displayName" prop="displayName">
                    <a-input
                        v-model="form.displayName"
                        placeholder="请输入显示名称"
                    />
                </a-form-model-item>
                <a-form-model-item label="描述" ref="description" prop="description">
                    <a-input
                        v-model="form.description"
                        placeholder="请输入描述"
                    />
                </a-form-model-item>
                <a-form-model-item label="允许的访问令牌签名算法" ref="allowedAccessTokenSigningAlgorithms" prop="allowedAccessTokenSigningAlgorithms">
                    <a-input
                        v-model="form.allowedAccessTokenSigningAlgorithms"
                        placeholder="请输入允许的访问令牌签名算法"
                    />
                </a-form-model-item>
                <a-form-model-item label="在发现文档中显示" ref="showInDiscoveryDocument" prop="showInDiscoveryDocument">
                    <a-checkbox v-model="form.showInDiscoveryDocument" name="在发现文档中显示" @change="handleSChange">
                    </a-checkbox>
                </a-form-model-item>
                <a-form-model-item label="启用" ref="enabled" prop="enabled">
                    <a-checkbox v-model="form.enabled" name="启用">
                    </a-checkbox>
                </a-form-model-item>
                <a-form-model-item label="Scopes" ref="Scopes" prop="Scopes" v-if="form.id ? true : false">
                    <a-select
                      mode="multiple"
                      v-model="form.scopes"
                      style="width: 100%"
                      placeholder="Please select"
                    >
                      <a-select-option v-for="item in apiScope" :key="item.id" :value="item.name">
                        {{ item.displayName }}
                      </a-select-option>
                    </a-select>
                </a-form-model-item>
            </a-form-model>
        </a-tab-pane>
        <a-tab-pane key="2" tab="声明" force-render>
            <a-transfer
                :data-source="mockData"
                :titles="['不拥有声明', '拥有声明']"
                :target-keys="targetKeys"
                :selected-keys="selectedKeys"
                :render="item => item.title"
                @change="handleChangeAAAA"
                @selectChange="handleSelectChange"
                />
        </a-tab-pane>
        <a-tab-pane key="3" tab="Secrete" v-if="form.id ? true : false">
           <a-form-model
                :model="sampleSecret"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-model-item label="key" ref="key" prop="key">
                    <a-select v-model="sampleSecret.type">
                      <a-select-option value="SharedSecret">
                        SharedSecret
                      </a-select-option>
                      <a-select-option value="X509Thumbprint">
                        X509Thumbprint
                      </a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="描述" ref="description" prop="description">
                    <a-input
                        v-model="sampleSecret.description"
                        placeholder="请输入值"
                    />
                </a-form-model-item>
                <a-form-model-item label="值" ref="value" prop="value">
                    <a-input
                        v-model="sampleSecret.value"
                        placeholder="请输入值"
                    />
                </a-form-model-item>
                <a-form-model-item label="到期" ref="expiration" prop="expiration">
                    <a-date-picker v-model="sampleSecret.expiration" :format="dateEFormat"/>
                </a-form-model-item>
            </a-form-model>
        </a-tab-pane>
        <a-tab-pane key="4" tab="属性" v-if="form.id ? true : false">
           <a-form-model
                :model="propertiesForm"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-model-item label="key" ref="key" prop="key">
                    <a-input
                        v-model="propertiesForm.key"
                        placeholder="请输入key"
                    />
                </a-form-model-item>
                <a-form-model-item label="值" ref="value" prop="value">
                    <a-input
                        v-model="propertiesForm.value"
                        placeholder="请输入值"
                    />
                </a-form-model-item>
            </a-form-model>
        </a-tab-pane>
     </a-tabs>
    </a-spin>
  </a-modal>
</template>

<script>
import moment from 'moment';
import { editApi,createApi, editApiHandle, getAllScopes } from "@/services/identityServer/identityServer";
export default {
  name: "TenantForm",
  data() {
    return {
      dateEFormat: 'YYYY-MM-DD',
      sampleSecret: {},
      checkNick: true,
      labelCol: { span: 7 },
      wrapperCol: { span: 10 },
      visible: false,
      confirmLoading: false,
      form: {},
      propertiesForm: {},
      rules: {
        name: [
          { required: true, message: "名称必须填写", trigger: "blur" },
        ],
      },
      mockData: [
          {
            key: "0",
            title: "sub"
          },
          {
            key: "1",
            title: "name"
          },
          {
            key: "2",
            title: "family_name"
          },
          {
            key: "3",
            title: "given_name"
          },
          {
            key: "4",
            title: "middle_name"
          },
          {
            key: "5",
            title: "nickname"
          },
          {
            key: "6",
            title: "preferred_username"
          },
          {
            key: "7",
            title: "profile"
          },
          {
            key: "8",
            title: "picture"
          },
          {
            key: "9",
            title: "website"
          },
          {
            key: "10",
            title: "gender"
          },
          {
            key: "11",
            title: "birthdate"
          },
          {
            key: "12",
            title: "zoneinfo"
          },
          {
            key: "13",
            title: "locale"
          },
          {
            key: "14",
            title: "updated_at"
          },
          {
            key: "15",
            title: "email"
          },
          {
            key: "16",
            title: "email_verified"
          },
          {
            key: "17",
            title: "email_verified"
          },
          {
            key: "18",
            title: "phone_number"
          },
          {
            key: "19",
            title: "phone_number_verified"
          },
          {
            key: "20",
            title: "test"
          },
          {
            key: "21",
            title: "名1"
          },
          {
            key: "22",
            title: "role"
          },
      ],
      targetKeys: [],
      selectedKeys: [],
      propId: '',
      apiScope: [],
      apiScopeMap: {}
    };
  },
  created() {
  },
  methods: {
    moment,
    handleChangeAAAA(nextTargetKeys) {
      this.targetKeys = nextTargetKeys;
    },
    handleSelectChange(sourceSelectedKeys, targetSelectedKeys) {
      this.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys];
    },
    handleSChange(e) {
      this.form.showInDiscoveryDocument  = e.target.checked;
    },
    openModal(model){
      this.visible = true;
      this.targetKeys = []
      this.propertiesForm = {}
      if(model && model.id){
        this.propId = model.id
        this.getFormData(model.id);
        this.getScopes();
      } else {
        this.propId = '';
        this.form = {
          userClaims: []
        }
      }
    },
    getScopes() {
      getAllScopes()
        .then(res => {
          this.apiScope = res;
          this.apiScope.forEach(item => {
            this.apiScopeMap[item.name] = true;
          })
        })
    },
    resetForm() {
      this.form = {};
    },
    getFormData(id) {
      this.confirmLoading = true;
      editApi(id).then((res) => {
        this.form = {
          ...res,
          scopes: res.scopes.map(i=>i.scope).filter(i=>this.apiScopeMap[i])
        };
        let userClaims = res.userClaims
        let checked = []
        userClaims.forEach(e=>{
            checked.push(e.type)
        })
        let filterData = this.mockData.filter(item => { return checked.includes(item.title); });
        filterData.forEach(e=> {
            this.targetKeys.push(e.key)
        })
      }).finally(()=>{
        this.confirmLoading = false
      });
    },
    handleCancel() {
      this.visible = false
      this.currentStep = 0
      this.$refs.ruleForm.clearValidate()
    },
    handleOk() {
      const form = this.$refs.ruleForm;
      // this.confirmLoading = true;
      if(this.propId){ 
          form.validate((valid) => {
            if (valid) {
              this.form.userClaims = []
              if(this.targetKeys.length>0) {
                  
                  let filterData = this.mockData.filter(item => { return this.targetKeys.includes(item.key); });
                  
                  filterData.forEach(e=> {
                      let info = {}
                      info.type =  e.title
                      this.form.userClaims.push(info)
                  })
              }
              if(this.sampleSecret.expiration) {
                this.sampleSecret.expiration = moment(this.sampleSecret.expiration).format('YYYY-MM-DD')
              }
              let SampleProperty = {
                  key : this.propertiesForm.key ? this.propertiesForm.key : '',
                  value : this.propertiesForm.value ? this.propertiesForm.value : '',
              }
              let SampleSecret = {
                  type : this.sampleSecret.type ? this.sampleSecret.type : '',
                  description : this.sampleSecret.description ? this.sampleSecret.description : '',
                  value : this.sampleSecret.value ? this.sampleSecret.value : '',
                  expiration : this.sampleSecret.expiration ? this.sampleSecret.expiration : '',
              }
              let values = {...this.form}
              values.sampleProperty = SampleProperty
              values.sampleSecret = SampleSecret
              values.scopes = this.form.scopes.map(item => {
                return { scope: item }
              })
              editApiHandle(this.propId,values)
                  .then((res) => {
                    this.visible = false;
                    form.resetFields();
                    this.$message.info("操作成功");
                    this.$emit('ok')
                  })
                  .finally(() => {
                    this.confirmLoading = false;
                  });
            } else {
              this.confirmLoading = false;
            }
          });
      }else {
        form.validate((valid) => {
        if (valid) {
            this.form.userClaims = []
          if(this.targetKeys.length>0) {
            
            let filterData = this.mockData.filter(item => { return this.targetKeys.includes(item.key); });
            
            filterData.forEach(e=> {
                let info = {}
                info.type =  e.title
                this.form.userClaims.push(info)
            })
          }
          let values = {
                name: this.form.name,
                displayName: this.form.displayName,
                description: this.form.description,
                showInDiscoveryDocument: this.form.showInDiscoveryDocument,
                allowedAccessTokenSigningAlgorithms: this.form.allowedAccessTokenSigningAlgorithms,
                userClaims:this.form.userClaims
          }
          createApi(values)
            .then((res) => {
              this.visible = false;
              form.resetFields();
              this.$message.info("操作成功");
              this.$emit('ok')
            })
            .finally(() => {
              this.confirmLoading = false;
            });
        } else {
          this.confirmLoading = false;
        }
      });
      }
      
    }
  },
};
</script>

<style scoped>
</style>